<script setup>
import {useRouter} from "vue-router";
import {ref, onMounted, onBeforeMount} from "vue";
import useUserInformationStore from '@/stores/Information/index.js'
import useTokenStore from "@/stores/User/token.js";

const Token = useTokenStore()
// 引入图标
import {Calendar, Edit, Location, PhoneFilled, UserFilled} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import axios from "axios";

const store = useUserInformationStore()
// 异步获取数据的函数
const fetchUserDataAndCity = async () => {
  try {
    await store.getUserData();
    console.log(store.userData)
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

// 在组件挂载时调用
onMounted(fetchUserDataAndCity);

const router = useRouter()
// 默认头像
const defaultAvatar = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png')
// 返回上一页
const handleBack = () => {
  router.back()
}

// 弹窗 修改用户信息
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const handleSubmit = async (form) => {
  console.log(JSON.stringify(form));
  const config = JSON.stringify({
    "image": form.image,
    "nickname": form.nickname,
    "gender": Number(form.gender),
    "birthday": form.birthdays,
    "phone_number": form.phoneNumber,
    "email": form.email
  })
  if (store.userData.gender === '1') {
    store.userData.gender = '男'
  } else if (store.userData.gender === '2') {
    store.userData.gender = '女'
  }
  try {
    await axios({
      method: 'put',
      url: '/user',
      baseURL: 'http://localhost:8080',
      data: config,
      headers: {
        'Content-Type': 'application/json',
        'token': localStorage.getItem('token') || Token.loginToken,
      }
    })
        .then(res => {
          if (res.data.code === 10200) {
            ElMessage({
              message: '修改成功',
              type: 'success',
            });
          } else if (res.data.code === 10205) {
            ElMessage({
              message: '未登录',
              type: 'warning',
            });
            router.push("/login")
          }
          console.log(res)
        })
  } catch (e) {
    ElMessage({
      message: '修改失败',
      type: 'error',
    });
    console.log('修改失败', e)
  } finally {
    dialogFormVisible.value = false
  }
}
</script>

<template>
  <div class="information">
    <h1>
      <i class="iconfont icon-fanhui4"
         @click="handleBack"
      ></i>
    </h1>
    <div class="information_main">
      <el-avatar class="information_avatar" :size="100"
                 :src="store.userData.image?store.userData.image:defaultAvatar"/>
      <el-input
          disabled
          class="el-input-date"
          v-model="store.userData.nickname">
        <template #prepend>昵称</template>
        <template #append>
          <el-icon>
            <Edit/>
          </el-icon>
        </template>
      </el-input>
      <el-input
          disabled
          class="el-input-date"
          v-model="store.userData.gender">
        <template #prepend>性别</template>
        <template #append>
          <el-icon>
            <UserFilled/>
          </el-icon>
        </template>
      </el-input>
      <el-input
          disabled
          class="el-input-date"
          v-model="store.userData.birthdays">
        <template #prepend>生日</template>
        <template #append>
          <el-icon>
            <Calendar/>
          </el-icon>
        </template>
      </el-input>
      <el-input
          disabled
          class="el-input-date"
          v-model="store.userData.phoneNumber">
        <template #prepend>手机号</template>
        <template #append>
          <el-icon>
            <PhoneFilled/>
          </el-icon>
        </template>
      </el-input>
      <el-input
          disabled
          class="el-input-date"
          v-model="store.userData.email">
        <template #prepend>邮箱：</template>
        <template #append>
          <el-icon>
            <Location/>
          </el-icon>
        </template>
      </el-input>
    </div>

    <div class="cat_edit">
      <el-button type="primary" @click="dialogFormVisible = true">修改信息</el-button>
    </div>

    <!--修改弹窗-->
    <el-dialog v-model="dialogFormVisible" title="修改个人信息" width="700">
      <div style="width: 500px;margin: 0 auto">
        <el-form :model="store.userData">
          <el-form-item label="头像" :label-width="formLabelWidth">
            <el-input v-model="store.userData.image" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="昵称" :label-width="formLabelWidth">
            <el-input v-model="store.userData.nickname" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="性别" :label-width="formLabelWidth">
            <el-select v-model="store.userData.gender" placeholder="请选择你的性别">
              <el-option label="男" value="1"/>
              <el-option label="女" value="2"/>
            </el-select>
          </el-form-item>
          <el-form-item label="生日" :label-width="formLabelWidth">
            <el-date-picker v-model="store.userData.birthdays" type="date" placeholder="选择日期"/>
          </el-form-item>
          <el-form-item label="手机号" :label-width="formLabelWidth">
            <el-input v-model="store.userData.phoneNumber" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth">
            <el-input v-model="store.userData.email" autocomplete="off"/>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="handleSubmit(store.userData)">
            修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.information {
  width: 1535px;
  height: 100vh;
  margin: 0 auto;
  overflow: hidden;

  h1 {
    i {
      cursor: pointer;
      font-size: 40px;
      font-weight: bold;
    }
  }

  .information_main {
    width: 500px;
    margin: 0 auto;
    display: flex;
    flex-direction: column;

    .information_avatar {
      margin: 0 auto 20px;
    }

    .el-input-date {
      margin-bottom: 50px;
      height: 60px !important;
      font-size: 20px;
    }

  }

  .cat_edit {
    width: 300px;
    height: 300px;
    display: flex;
    justify-content: center;
    margin: 0 auto;

    .el-button {
      margin-top: 20px;
      width: 200px;
      height: 60px;
      font-size: 20px;
    }
  }
}
</style>